import React, { memo } from 'react';
import { Table, Form, Input, Rate, Icon, Tooltip } from 'antd';
import DescItem from '@/pages/Recruitment/Setting/containers/EvaluationTable/DescItem';

import styles from './index.less';

// 组件用于面试准备、面试记录能力、展示面试详情评估表控件 type控制面试准备缩小样式
const AssessFrom = ({
    value = {},
    onChange = () => {},
    form = {},
    // type = 'prepare',
    settings = {},
    detailShow = false,
    tableIdName = 'id',
    tableTitle = '',
    isExpandedRowRender = false,
    ...rest
}) => {
    const { selectKeys = [] } = value;
    const { checkIs = 1, starIs = 0, scoreIs = 0, textIs = 0, passScoreIs = 0, checkDisabled, isPrepared } = settings; // 1代表需要该功能
    // const { checkIs = 0, starIs = 1, scoreIs = 1, textIs = 1, passScoreIs = 1 } = settings; // 1代表需要该功能
    const { getFieldDecorator } = form;
    const { formName = '产品经理专业评估', formId = '', formItems = [] } = value;
    const countRule = scoreType => {
        let total = 0;
        formItems.forEach(item => {
            total += +(item[scoreType] || 0);
        });
        return total;
    };
    const getScore = record => {
        let score = 0;
        [...new Set(record.eval_names)].forEach(x => {
            score += +record[x];
        });
        return (score / [...new Set(record.eval_names)].length).toFixed(2);
    };
    const totalScore = () => {
        let total = 0;
        formItems.forEach(x => {
            total += +getScore(x);
        });
        return total;
    };
    const totalPassScore = () => {
        let total = 0;
        formItems.forEach(x => {
            total += +x.passScore;
        });
        return total;
    };
    const getDetailLevel = arrayData => {
        const { itemDesc = [] } = arrayData;
        return itemDesc.map(item => (
            <div>
                {item.scoreValue}分 ({item.rankValues}){item.comment}
            </div>
        ));
    };
    const scoreShow = () => {
        if (detailShow) {
            return (
                <div style={{ margin: '8px 0 16px 0' }}>
                    得分/达标/总分：<span className={styles.color_85}>{totalScore()}</span>/
                    <span>{totalPassScore()}</span>/<span>{5 * formItems.length}</span>
                </div>
            );
        }
        return (
            <div style={{ margin: '8px 0 16px 0' }}>
                得分/达标/总分：<span className={styles.color_85}>{countRule('itemEvaluateScore')}</span>/
                <span>{countRule('passScore')}</span>/<span>{5 * formItems.length}</span>{' '}
            </div>
        );
    };
    const handleDemandChange = (newText, record, changeType) => {
        const { itemId } = record;
        const getIndex = formItems.findIndex(x => x.itemId === itemId);
        const newFormItems = [
            ...formItems.slice(0, getIndex),
            {
                id: formItems[getIndex].id,
                itemId: formItems[getIndex].itemId,
                itemName: formItems[getIndex].itemName,
                passScore: formItems[getIndex].passScore,
                itemEvaluateScore: changeType === 'rate' ? newText : formItems[getIndex].itemEvaluateScore || 0,
                itemEvaluateReason: changeType === 'rate' ? formItems[getIndex].itemEvaluateReason : newText,
                itemDesc: formItems[getIndex].itemDesc,
                history: formItems[getIndex].history
            },
            ...formItems.slice(getIndex + 1)
        ];
        console.log('当前的table数据', newFormItems);
        onChange({
            formId,
            formName,
            formItems: newFormItems
        });
    };

    let otherItem = {}; // 表格是否显示达标分
    if (passScoreIs) {
        otherItem = {
            title: '达标分',
            dataIndex: 'passScore'
        };
    } else {
        otherItem = {};
    }

    let columns;

    if (isPrepared) {
        columns = [
            {
                title: '评估项',
                dataIndex: 'itemName'
            },
            {
                title: '总分',
                dataIndex: 'id',
                width: 60,
                render: () => '5'
            },
            {
                title: '评分标准',
                dataIndex: 'itemDesc',
                render: text => <DescItem text={text} />
            }
            // {
            //     title: '我的备注',
            //     dataIndex: 'itemEvaluateReason',
            //     render: () => '--'
            // }
        ];
    } else {
        columns = [
            {
                title: '评估项目',
                dataIndex: 'itemName',
                render: (text, record) => (
                    <>
                        {text}
                        <Tooltip placement="rightTop" title={getDetailLevel(record)} overlayStyle={{ maxWidth: 430 }}>
                            <Icon type="question-circle-o" style={{ marginLeft: '5px' }} />
                        </Tooltip>
                    </>
                )
            },
            { ...otherItem },
            {
                title: '我的评分',
                dataIndex: 'itemEvaluateScore',
                width: 200,
                render: (text, record) => (
                    <div>
                        {starIs ? (
                            <Form.Item>
                                {getFieldDecorator(`${record.itemId}-${formId}-itemEvaluateScore`, {
                                    initialValue: text || undefined,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请打分'
                                        },
                                        {
                                            validator(_, val, callback) {
                                                if (val < 0.5) {
                                                    callback('请打分');
                                                } else {
                                                    callback();
                                                }
                                            }
                                        }
                                    ]
                                })(
                                    <Rate
                                        allowHalf
                                        onChange={e => {
                                            handleDemandChange(e, record, 'rate');
                                        }}
                                    />
                                )}
                                {text ? <span style={{ marginLeft: 8 }}>{text}</span> : null}
                            </Form.Item>
                        ) : (
                            <Rate disabled defaultValue={0} />
                        )}
                    </div>
                )
            },
            {
                title: '我的备注',
                dataIndex: 'itemEvaluateReason',
                render: (text, record) => (
                    <div>
                        {textIs ? (
                            <Form.Item>
                                {getFieldDecorator(`${record.itemId}-${formId}-itemEvaluateReason`, {
                                    initialValue: text,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请填写我的备注'
                                        },
                                        {
                                            max: 100,
                                            message: '限制100个字符长度'
                                        },
                                        {
                                            pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                            message: '此处不能输入空格'
                                        }
                                    ]
                                })(
                                    <Input
                                        placeholder="请输入"
                                        autoComplete="off"
                                        style={{ width: '100%' }}
                                        onChange={e => handleDemandChange(e.target.value, record, 'evaluate')} // 加入formgetfield获取
                                    />
                                )}
                            </Form.Item>
                        ) : (
                            '--'
                        )}
                    </div>
                )
            }
        ];
    }

    let newPart = [];
    if (detailShow) {
        formItems.forEach(x => {
            newPart = [...newPart, ...x.eval_names];
        });
    }

    // 动态增加面试官评分数据
    const interviewName = [...new Set(newPart)].map(x => ({
        title: x,
        // dataIndex: x || '--',
        render: (text, record) => (
            <Tooltip title={record.itemEvaluateReason}>
                <span>{record[x] !== undefined ? record[x] : '--'}</span>
            </Tooltip>
        )
    }));
    const detailColunms = [
        {
            title: '评估项目',
            dataIndex: 'itemName',
            width: '30.5%',
            render: (text, record) => (
                <span>
                    {text}
                    <Tooltip placement="rightTop" title={getDetailLevel(record)} overlayStyle={{ maxWidth: 430 }}>
                        <Icon type="question-circle-o" style={{ marginLeft: '5px' }} />
                    </Tooltip>
                </span>
            )
        },
        ...interviewName,
        {
            title: '达标分',
            dataIndex: 'passScore'
        },
        {
            title: '平均分',
            render: (text, record) => <span>{getScore(record)}</span>
        }
    ];
    const [selectedRowKeys, setSelectedRowKeys] = React.useState(selectKeys);
    const onSelectChange = keys => {
        console.log('===============================================>keys', keys);
        setSelectedRowKeys(keys);
        onChange({
            formId,
            formName,
            formItems,
            selectKeys: keys
        });
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
        getCheckboxProps: () => ({ disabled: checkDisabled })
    };
    let checkShow; // 动态控制是否勾选功能
    if (checkIs) {
        checkShow = {
            rowSelection
        };
    } else {
        checkShow = {};
    }
    const expandedRowRender = record => {
        const expandedColumns = [
            {
                title: '评估项目',
                dataIndex: 'date',
                key: 'date',
                width: '46%',
                render: (_, tableRecord) => `${tableRecord.evaluateEmployeeName}（${tableRecord.interviewRoundName}）`
            },
            {
                title: '达标分',
                dataIndex: 'itemEvaluateScore',
                key: 'itemEvaluateScore',
                width: '20%'
            },
            {
                title: '我的备注',
                dataIndex: 'itemEvaluateReason',
                key: 'itemEvaluateReason'
            }
        ];
        return (
            <Table columns={expandedColumns} showHeader={false} dataSource={record.history || []} pagination={false} />
        );
    };
    React.useEffect(() => {
        console.log('formItems', formItems);
    }, [formItems]);
    return (
        <div className={styles.interAddPostMainTable}>
            <div>
                <span className={styles.title}>{formName}</span>
                {tableTitle && <span>（{tableTitle}）</span>}
            </div>
            {scoreIs ? scoreShow() : ''}
            <Table
                // rowSelection={rowSelection}
                rowClassName={record => (record.history ? '' : styles.tableHideRowClassName)}
                rowKey={tableIdName}
                pagination={false}
                columns={detailShow ? detailColunms : columns}
                dataSource={formItems}
                expandedRowRender={isExpandedRowRender ? expandedRowRender : null}
                {...checkShow}
                {...rest}
            />
        </div>
    );
};
export default memo(AssessFrom);
